const host = 'http://511.huyingying.top:8000';
function btnAdd(){
    location.href='./addOrEdit.html';
}
function btnEdit(id){
    location.href = './addOrEdit.html?id=' + id
}
function btnDel(id){
    console.log('删除');
    if(confirm(`是否确认删除${id}`)){
        axios.delete(`${host}/blogs/${id}`).then((res) => {

            let data = res.data;
            console.log(data.code);
            
            if(data.code===1000){
                let tr = document.querySelector(`.blog${id}`);
                console.log(tr);
                
                tr.remove();
            }else{
                alert(`${data.msg}`)
            }
            
        })
    }
    
}
async function btnFilter(){
    console.log('过滤');
    let keyword = $('input[name=keyword]').val().trim();
    let res = await axios.get(`${host}/blogs?keyword=${keyword}`);
    console.log(res);
    
    let blogs = res.data.data;
    $('tr[class^=blog]').remove();
    blogs.forEach(item => {
        let html = `
                        <tr class="blog${item.id}">
                                <td>${item.id}</td>
                                <td>${item.title}</td>
                                <td>${item.author}</td>
                                <td>
                                    <input type="button" value="编辑" onclick=btnEdit(${item.id})>
                                    <input type="button" value="删除" onclick=btnDel(${item.id})>
                                </td>
                            </tr>
                        `
            $('tbody').append(html)
    });
}
function btnSave(){
    console.log('保存');
    let id = new URLSearchParams(location.search).get('id') || 0 ;
    let title = $('input[name=title]').val().trim();
    let author = $('input[name=author').val().trim();
    let obj = {
        title:title,
        author:author
    }
    if(id>0){
        axios.put(`${host}/blogs/${id}`,obj).then((res) => {
            if (res.data.code === 1000) {
                location.href = './index.html';
            }else{
                confirm(res.data.msg)
            }
        })
    }else{
        axios.post(`${host}/blogs`,obj).then((res) => {
            if (res.data.code === 1000) {
                location.href = './index.html';
            }else{
                confirm(res.data.msg)
            }
        })
    }
    
    
}
function btnNo(){
    console.log('取消');
    location.href = './index.html';
}
